<template>
  <view class="page-container">
    <HeaderBar
        title="订单填写"
		@click="handleGoBack"
        navBarBgc="linear-gradient(180deg, rgba(186,209,194,1) 0%, rgba(207,223,212,1) 33%, rgba(230,238,233,1) 100%);"
    ></HeaderBar>
    <view class="content-container">
      <view class="product-name">{{directTrain.routeName}}{{carData.name}}</view>
      <view class="visit-container flex justify-between ">
        <view class="visit-time">{{carData.date}} {{carData.carType}}({{carData.seats}}座) {{carData.time}}发车</view>
        <view class="btn-back" @click="handleGoBack">返回修改</view>
      </view>
      <view class="product-list-container">
        <charteredBus :Busdata="carData" @getordernum='ordernum'></charteredBus>
      </view>
      <view class="tourist-container mt40">
        <view class="tip-title">需填{{carData.taveNum}}位游客</view>
        <view class="tourist-info-container flex items-center">
          <view
              v-for="(item,index) in touristInfoList"
              :key="index"
              @click="handleUser(item,index)"
              :class="['tourist-info', choiceUserId === index ? 'active' : '']"
          >
            {{item.name}}
          </view>
          <view class="tourist-info" @click="addTourList">选择/新增></view>
        </view>
		<view v-show="directTrain.passengers.length" v-for="iten in directTrain.passengers" >
			<view class="chooseUser">
				<text>姓名：{{iten.name}}</text>
				<view class="arrowright">
					<!-- <wd-icon name="arrow-right" size="22px"></wd-icon> -->
				</view>
			</view> 
			<view class="contact-container">
				<text>联系电话</text>
				<input v-model="iten.phone" placeholder="请输入手机号" class="input-box"/>
			</view>
		</view>
      </view>
      <view class="safe-area-content"></view>
    </view>

	<AddTourist
	  :showAddTourist="showAddTourist"
	  :touristInfoList="touristInfoList"  
	  @close="closeAddTourist"
	  @queryTouristList="queryTouristList(false)"
	></AddTourist>
    <view class="btn-bottom-container">
      <view class="top-container flex ">
        <view class="price">￥ {{directTrain.payAmount}}</view>
        <view class="right-container">
          <view class="price-detail-tip" @click="showdetails">
            <text>明细</text>
            <wd-icon name="arrow-down" size="22px"></wd-icon>
          </view>
          <view class="btn" @click="handNavReservation">去支付</view>
        </view>
      </view>
      <view class="safe-content" :style="{height: safeInsert + 'px'}"></view>
    </view>
	<wd-action-sheet v-model="isShowDetails" @close="closedetails">
		  <view style="padding: 15px 15px 150px 15px;">
			  <view class="isDetails"> <text>车型名称 : {{directTrain.carModelName}}</text> </view>
			  <view class="isDetails"> <text>路线名称 : {{directTrain.routeName}}</text> </view>
			  <view class="isDetails"> <text>发车时间 : {{carData.date}} {{directTrain.departureTime}} </text> </view>
			  <view class="isDetails"> <text>合计金额 : {{directTrain.totalAmount}}元</text> </view>
			  <view class="isDetails"> <text>票数 : {{directTrain.availableNum}}</text> </view>
			  <view class="isDetails"> <text>优惠金额 : {{directTrain.discountAmount}}元</text> </view>
			  <view class="isDetails"> <text>实付金额 : {{directTrain.payAmount}}元</text> </view>
		  </view>
		  <view class="btn-bottom-container">
			<view class="top-container flex ">
			  <view class="price">￥  {{directTrain.payAmount}}</view>
			  <view class="right-container">
				<view class="price-detail-tip" @click="showdetails">
				  <text>明细</text>
				  <wd-icon name="arrow-down" size="22px"></wd-icon>
				</view>
				<view class="btn" @click="handNavReservation">去支付</view>
			  </view>
			</view>
			<view class="safe-content" :style="{height: safeInsert + 'px'}"></view>
		  </view>
		</wd-action-sheet>
  </view>
</template>

<script setup>
  import {ref,reactive} from "vue";
  import {touristList} from "@/api/common";
  import {onLoad} from "@dcloudio/uni-app";
  import HeaderBar from "@/components/HeaderBar/index.vue";
  import charteredBus from "@/components/charteredBus/index.vue";
  // import addTourist from "@/components/AddTourist/index.vue"; 
  import {commitOrder,toPay} from "@/trafficSubPack/api/trafficHome";

  const touristInfoList = ref([]);
  const isShowDetails = ref(false)

  const carData =reactive({
	  data:{},
	  name:'',
	  date:'',
	  carType:'',
	  time:'',
	  seats:'',
	  price:0,
	  taveNum:1
  })

  const directTrain = ref({
  	userId:999,
  	contactName:'sulie',//用户名字
  	userType:0,//用户类型
  	contactPhone:'19999999999',//用户电话
  	vehicleType:2,//用车类型
  	carModelId:'',//车型
  	carModelName:'',//车型名称
  	departureTime:'',//发车时间
  	vehicleStartTime:'',//用车时间
	availableNum:1,//数量
	totalNum:1,//数量
  	totalAmount:'',//合计金额
  	payAmount:'',//实付金额
  	discountAmount:0,//优惠金额
  	routeId:'',//路线ID
  	routeName:'',//路线名称
  	merchantId:"",//服务商ID
  	merchantName:'',//服务商名称
	productId:'',//产品id
	productName:'',//产品名称
  	type:2,//订单类型：2|交通
  	memo:'',//订单备注
	status:0,
	passengers:[]
  })

  const safeInsert = ref(0);
  const choiceUserId = ref(null);
  const showAddTourist = ref(false); 


  const handleGoBack = () => {
    uni.navigateBack();
  };

  const ordernum = (data)=>{ 
	carData.taveNum = data
	directTrain.value.availableNum = data
	directTrain.value.totalNum = data
	directTrain.value.totalAmount = carData.price * data
	directTrain.value.payAmount = directTrain.value.totalAmount - directTrain.value.discountAmount

  }
  const handleUser = (data, index) => { 
	  const userdata = {
		name:data.name,//乘客姓名//
		phone:data.tel,//乘客电话//
		idCard:data.idCard,//身份证号码//
		unitPrice:carData.price,//单价
		discountAmount:0//优惠金额
	  } 
	  if (choiceUserId.value === index) {
	      // 再次点击取消选择
	      choiceUserId.value = null;
	      directTrain.value.passengers = [];
	  } else {
	      choiceUserId.value = index;
	      directTrain.value.passengers = [userdata];
	  }
    //   if (choiceUserId.value.includes(index)) {
    //       // 如果已经选中，则取消选中
    //       choiceUserId.value = choiceUserId.value.filter(id => id !== index);
		  // directTrain.value.passengers = directTrain.value.passengers.filter(id => id.idCard !== data.idCard);
    //   } else {
    //       // 否则添加到选中列表
    //       choiceUserId.value.push(index);
		  // directTrain.value.passengers.push(userdata)
    //   } 
	  // carData.taveNum = directTrain.value.passengers.length
  };
  const addTourList = () => {
    showAddTourist.value = true;
  };
  const closeAddTourist = () => {
    showAddTourist.value = false;
  };
  const handNavReservation = () => { 
	// if(carData.taveNum == directTrain.value.passengers.length){
		commitOrder(directTrain.value).then(res=>{
			console.log(res,"crateOrder")
			handleToPay(res.result.orderId);
		})
	// } else if(carData.taveNum >= directTrain.value.passengers.length) {
	// 	uni.showToast({
	// 		title:'请添加乘客数量',
	// 		icon:"none"
	// 	})
	// } else if(carData.taveNum <= directTrain.value.passengers.length) {
	// 	uni.showToast({
	// 		title:'请添加票数',
	// 		icon:"none"
	// 	})
	// } 
  };

  const handleToPay = async (id) => {
  	// #ifdef MP-WEXIN
  	// #endif
  	await toPay({type:"jsapi",id}).then(res => {
		// console.log("payAmount = ", directTrain.value.payAmount)

  	  let { appId,nonceStr, packageValue,paySign,signType,timeStamp } = res.result;
  	  uni.navigateTo({
  		url:`/ticketSubPack/pages/PaymentOrder/index?totalPrice=${directTrain.value.payAmount}&timeStamp=${timeStamp}&nonceStr=${nonceStr}&packageValue=${encodeURIComponent(packageValue)}&signType=${signType}&paySign=${encodeURIComponent(paySign)}&orderId=${id}`
  	  })
  	 /* wxPay(timeStamp,nonceStr,packageValue,signType,paySign);*/
  	});
  };
  
  const showdetails = () => {
    isShowDetails.value = !isShowDetails.value;
  };
  const closedetails = () => {
    isShowDetails.value = false;
  };
  const queryTouristList = async (isShowLoad) => {
    await touristList({pageSize:99,userId:2}).then(res => {
      // if(res && res.length > 0) {
      //   res.forEach(item => {
      //     item.isChecked = false;
      //     item.tipContent = "";
      //   });
      // }
      touristInfoList.value = res.result;
      directTrain.value.contactName = touristInfoList.value[0].name;
      directTrain.value.contactPhone = touristInfoList.value[0].tel;
	  // console.log(touristInfoList.value);
      // if(isShowLoad && crowdProductList.value && crowdProductList.value.length > 0) {
      //   choiceProduct.value = crowdProductList.value[0];
      // }
      // idCardValidate();
    });
  };
  onShow(async() => {
    await queryTouristList(true);
  }); 
  onLoad((options) => {
    safeInsert.value = uni.getSystemInfoSync().safeAreaInsets.bottom
	if (options.yudingData) {
		const getcarData = JSON.parse(decodeURIComponent(options.yudingData));
		// console.log('getcarData',getcarData);
		carData.data = getcarData
		carData.name = getcarData.trafficInfo.name
		carData.carType = getcarData.carModel.find(item => item.code == getcarData.trafficInfodetail.code)?.name || '';
		carData.seats = getcarData.trafficInfodetail.seats
		carData.price = getcarData.trafficInfodetail.price
		carData.date = getcarData.chooseDate
		carData.time = getcarData.choiceCarTime

		directTrain.value.carModelId = getcarData.trafficInfodetail.id
		directTrain.value.carModelName = getcarData.carModel.find(item => item.code == getcarData.trafficInfodetail.code)?.name || '';
		directTrain.value.departureTime = getcarData.choiceCarTime
		directTrain.value.vehicleStartTime = getcarData.chooseDate + ' 00:00:00'
		directTrain.value.totalAmount = getcarData.trafficInfodetail.price
		directTrain.value.payAmount = directTrain.value.totalAmount - directTrain.value.discountAmount
		// directTrain.value.discountAmount = getcarData.trafficInfodetail.price
		directTrain.value.routeId = getcarData.routeId
		directTrain.value.routeName = getcarData.routeName
		directTrain.value.productId = getcarData.trafficInfo.id
		directTrain.value.productName = getcarData.trafficInfo.name
		directTrain.value.merchantId = getcarData.trafficInfo.merchantId
		directTrain.value.merchantName = getcarData.trafficInfo.merchantName
	} 
  });


</script>

<style lang="scss" scoped>
  .page-container {
    .content-container {
      padding: 20rpx 27.5rpx;
      width: auto;
      min-height: 100vh;
      background: linear-gradient(180deg, rgba(228, 237, 231, 1) 0%, rgba(238, 239, 231, 1) 18%, rgba(238, 239, 231, 1) 100%);
      .product-name {
        font-size: 41.5rpx;
        font-weight: bold;
      }
      .visit-container {
        padding: 26.5rpx 0 80rpx 0;
        .visit-time {
          font-size: 25rpx;
          color: #2B2B24;
        }
        .btn-back {
          font-size: 25rpx;
		  // margin-top: 10rpx;
          padding: 2rpx;
          border-radius: 10.5rpx;
          border: 1px solid #26704E;
          color: #000000;
        }
      }
      .product-list-container {
        padding: 0 32.5rpx;
        border-radius: 10.5rpx;
        background: #FFFFFF;
      }
      .tourist-container {
        padding: 46rpx 32rpx  20rpx 32rpx;
        border-radius: 10.5rpx;
        background: #FFFFFF;
        .tip-title {
          font-size: 33.5rpx;
          font-weight: bold;
        }
        .tourist-info-container {
          padding: 30rpx 0;
          flex-wrap: wrap;
          .tourist-info {
            font-size: 25rpx;
            border-radius: 10.5rpx;
            border: 1rpx solid #1B9C61;
            padding: 18rpx 63rpx;
            margin-right: 20rpx;
            margin-bottom: 20rpx;
            text-align: center;
          }
        }

		.active{
		  color: #FDFFEB !important;
		  background:#1B9C61 !important;
		}
        .tourist-input-container {
          padding: 30rpx 0;
          border-bottom: 1rpx solid #C0C2B3;
          .choose-product-name {
            font-size: 29rpx;
            font-weight: bold;
          }
          .number-tip {
            padding-top: 22.5rpx;
            font-size: 25rpx;
            color: #D33700;
          }
        }
		.chooseUser{
		  height: 30rpx;
		  display: flex;
		  align-items: center;
		  line-height: 30rpx;
		  justify-content: space-between;
		  .arrowright{
			  margin-top: 6rpx;
		  }
		}
        .contact-container {
          margin: 55rpx 0;
          padding: 15.5rpx;
          font-size: 25rpx;
          border-radius: 10.5rpx;
          background:#EEEFE7;
		  display: flex;
		  align-items: center;
		  gap: 30rpx;
        }
      }
      .safe-area-content {
        height: 200rpx;
      }
    }
	.isDetails{
		padding: 20rpx 0;
	}
    .btn-bottom-container {
      position: fixed;
      width: 100%;
      bottom: 0;
      left: 0;
      background: #fdffeb;
      .top-container {
        justify-content: space-between;
        align-items: center;
        padding: 32rpx 20rpx 0 59rpx;
        .price {
          font-size: 42rpx;
          font-weight: bold;
          color: #AA5413;
        }
        .right-container {
          display: flex;
          align-items: center;
          .price-detail-tip {
            display: flex;
            align-items: center;
            padding-right: 11rpx;
            text {
              font-size: 30rpx;
            }
          }
          .btn {
            border-radius: 10.5rpx;
            font-weight: bold;
            padding: 25rpx 32rpx;
            color: #FDFFEB;
            background: #AA5413;
          }
        }
      }
    }
  }
</style>
